require 'digest/sha1'

class User < ActiveRecord::Base
  
  has_many :messages
  belongs_to :chatroom
  
  validates_presence_of :name, :username
  validates_uniqueness_of :username
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def password
    @password
  end
  
  def password=(password)
    @password = password
    return if password.blank?
    create_salt
    self.password_hashed = User.encrypted_password(password, self.password_salt)
  end

  ## Private functions
  
  private  
  
  def self.authenticate(username, password)
    user = User.find_by_username(username)
    if user
      if user.password_hashed == User.encrypted_password(password, user.password_salt)
        return user
      else
        user = nil
        return user
      end
    end
  end
  
  def self.encrypted_password(password, salt)
    word = "chat"
    string_to_hash = password + salt + word
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_salt
    self.password_salt = self.object_id.to_s + rand.to_s
  end
  
  
  
end